package com.example.start;

import com.alibaba.fastjson.JSON;
import com.example.start.model.Root;
import com.example.dmcommom.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.TreeMap;

/**
 * @author license检查
 */
@Component
@EnableAsync
public class LicenseCliJob {
    private static Logger LOGGER = LoggerFactory.getLogger(LicenseCliJob.class);

    @Value("${license.sever}")
    private String sever;
    @Value("${license.key}")
    private String key;

    @Value("${license.whoAmI}")
    private String whoAamI;

    private static boolean verifySenseTimeLicense(String sever, String key, String whoAamI) {
        try {

            long timestamp = System.currentTimeMillis() / 1000;
            String nonce = HttpUtil.getRandomString();
            String whoami = whoAamI;

            StringBuilder sb = new StringBuilder("POST?");
            sb.append("timestamp").append("=").append(timestamp).append("&");
            sb.append("nonce").append("=").append(nonce).append("&");
            sb.append("whoami").append("=").append(whoami);

            TreeMap<String, Object> params = new TreeMap<String, Object>(); // TreeMap可以自动排序
            params.put("sign", HttpUtil.sign(sb.toString(), key, "HmacSHA256")); // 公共参数
            params.put("timestamp", timestamp); // 公共参数
            params.put("nonce", nonce); // 公共参数
            params.put("whoami", whoAamI); // 公共参数

            String json = HttpUtil.okHttpPost(sever, JSON.toJSONString(params));

            if (StringUtils.isNotEmpty(json)) {
                Root root = JSON.parseObject(json, Root.class);
                if (root != null
                        && root.getCode() == 0
                        && root.getData() != null) {

                    StringBuilder sbReturn = new StringBuilder("POST?");
                    sbReturn.append("timestamp").append("=").append(root.getData().getTimestamp()).append("&");
                    sbReturn.append("nonce").append("=").append(root.getData().getNonce()).append("&");
                    sbReturn.append("whoami").append("=").append(root.getData().getWhoami());

                    String checkSign = HttpUtil.sign(sbReturn.toString(), key, "HmacSHA256");

                    if (StringUtils.isNotEmpty(checkSign)
                            && checkSign.equals(root.getData().getSign())) ;
                    {
                        return true;
                    }
                }
            }
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.error("检查异常:{}",ex.getMessage());
            return false;
        }
    }

    /**
     * 每分钟检查检查一次
     */
//    @Scheduled(fixedDelayString = "10000")
//    @Async
    public void checkUserLicense() {
        try {
            boolean verifySenTimeRe = verifySenseTimeLicense(sever + "/v1/license/verify", key, whoAamI);
            if (!verifySenTimeRe) {
                LOGGER.info("Verify that the license -- > of sensetime expires and the system exits!");
                System.exit(0);
            }
        } catch (Exception ex) {
            LOGGER.error("验证license异常", ex.getMessage());
            System.exit(0);
        }
    }

}
